package dyyx.telnet;

import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelHandler.Sharable;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;

import java.net.InetAddress;
import java.time.LocalTime;
import java.util.Date;


@Sharable
public class TelnetServerHandler extends SimpleChannelInboundHandler<String> {

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        // Send greeting for a new connection.
    	
        ctx.write("Welcome to " + InetAddress.getLocalHost().getHostName() + "!\r\n");
        ctx.write("It is " + new Date() + " now.\r\n");
        ctx.flush();
        
    }

    @Override
    public void channelRead0(ChannelHandlerContext ctx, String request) throws Exception {
        // Generate and write a response.
        String response;
        boolean close = false;
        
        
        String recvtime = LocalTime.now().toString();
        long sleepTime = getSleepTime(request);
        System.out.println(LocalTime.now()+",recvmsg:"+request+",sleepTime="+sleepTime+","+Thread.currentThread()+","+ctx.channel());
        if(sleepTime>0){
        	Thread.sleep(sleepTime);
        }
                
        
        if (request.isEmpty()) {
            response = "Please type something.";
        } else if ("bye".equals(request.toLowerCase())) {
            response = "Have a good day!";
            close = true;
        } else {
            response = "Did you say '" + request + "'?";
        }
        
        String writetime = LocalTime.now().toString();

        response = "server.writetime="+writetime+",recvtime="+recvtime+","+response;
        response = response +","+Thread.currentThread()+","+ctx.channel()+","+ctx;
        response = response +","+ctx.executor()+","+ctx.executor().parent();
        response = response+"\r\n";


        // We do not need to write a ChannelBuffer here.
        // We know the encoder inserted at TelnetPipelineFactory will do the conversion.
        //  TODO write vs writeAndFlush
        ChannelFuture future = ctx.write(response);
        
        System.out.println(LocalTime.now()+",write,msg="+response);

        // Close the connection after sending 'Have a good day!'
        // if the client has sent 'bye'.
        if (close) {
            future.addListener(ChannelFutureListener.CLOSE);
        }
    }

    @Override
    public void channelReadComplete(ChannelHandlerContext ctx) {
        ctx.flush();
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
        cause.printStackTrace();
        ctx.close();
    }
    
    private static long getSleepTime(String str){
    	if(str==null){
    		return 0;
    	}
    	String tmp = "sleep";
    	if(!str.startsWith(tmp)){
    		return 0;
    	}
    	final int LEN = tmp.length();
    	final int len = str.length();
    	if(len<=LEN){
    		return 0;
    	}
    	str = str.substring(LEN);
    	try{
    	    return Long.parseLong(str);
    	}catch(Throwable e){
    		return 0;
    	}
    }
    
    
}
